package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.BomUserDao;
import com.xbongbong.saas.domain.entity.BomUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.BomTeamEnum;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.model.BomUserModel;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/2/1 14:33
 * @since v1.0
 */
@Service("bomUserModel")
public class BomUserModelImpl implements BomUserModel {

    @Resource
    private BomUserDao bomUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    @Override
    public Integer insert(BomUserEntity entity) throws XbbException {
        Integer result = bomUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_BOM_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_BOM_TEAM);
        paasEsModel.insert(saveDTO);
//        paasEsModel.insert(entity,IndexTypeEnum.IDX_SAAS_BOM_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    @Override
    public Integer update(BomUserEntity entity) throws XbbException {
        Integer result = bomUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_BOM_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_BOM_TEAM);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_BOM_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    @Override
    public List<BomUserEntity> findEntitys(Map<String, Object> param) {
        return bomUserDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return bomUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public BomUserEntity getByKey(Long key, String corpid) {
        return bomUserDao.getByKey(key, corpid);
    }

    @Override
    public Integer save(BomUserEntity bomUserEntity) throws XbbException {
        if (bomUserEntity.getId() == null || bomUserEntity.getId().equals(0L)) {
            bomUserEntity.setId(null);
            return insert(bomUserEntity);
        }
        return update(bomUserEntity);
    }

    @Override
    public Integer deleteByBomIdIn(List<Long> list, String corpid) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("bomIdIn",list);
        List<BomUserEntity> bomUserEntityList = findEntitys(map);
        Integer result = bomUserDao.deleteByBomIdIn(list, corpid);
        for (BomUserEntity entity : bomUserEntityList){
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_BOM_TEAM,entity.getDataId());
        }
        return result;
    }

    /**
     * 查询协同团队基础列表
     *
     * @param map 参数
     * @return 团队
     */
    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return bomUserDao.findBaseEntitys(map);
    }

    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return bomUserDao.getDataIdList(corpid,isMain,userId);
    }

    @Override
    public void delete(BomUserEntity bomUserEntity) throws XbbException{
        bomUserEntity.setDel(1);
        bomUserEntity.setUpdateTime((long) DateUtil.getInt());
        bomUserDao.update(bomUserEntity);
        paasEsModel.delete(bomUserEntity.getId(), bomUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_BOM_TEAM,bomUserEntity.getDataId());
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del) throws XbbException {
        bomUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(BomTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        bomUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(BomTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    @Override
    public void insertBatch(List<BomUserEntity> bomUserEntityList, boolean isImport) throws XbbException {
        bomUserDao.insertBatch(bomUserEntityList);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_BOM_TEAM, bomUserEntityList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_BOM_TEAM));
        }

//        for (BomUserEntity bomUserEntity : bomUserEntityList) {
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
//            insertDTO.setEsId(bomUserEntity.getCorpid() + "_" + bomUserEntity.getId());
//            insertDTO.setParent(bomUserEntity.getCorpid() + "_" + bomUserEntity.getDataId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(bomUserEntity, false, true));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
//            insertDTOList.add(insertDTO);
//        }
        if (isImport) {
            paasEsModel.insertBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        } else {
            paasEsModel.insertBatch(insertDTOList);
        }
    }

    /**
     * 通过Bom的id获取团队
     *
     * @param corpid 公司id
     * @param bomId  BomId
     * @return List
     * @author GuoJun.HU
     * @date 2019/4/19 15:39
     * @since V1.0
     */
    @Override
    public List<BomUserEntity> getBomUserListByBomId(String corpid, Long bomId) {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("bomId", bomId);
        return findEntitys(map);
    }

    @Override
    public Map<Long, String> batchDeleteById(String corpid, List<Long> removeIdList) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("idIn",removeIdList);
        List<BomUserEntity> bomUserEntityList = findEntitys(map);
        bomUserDao.batchDeleteById(corpid,removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<Long,String> bomUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (BomUserEntity entity : bomUserEntityList){
            bomUserMap.put(entity.getDataId(),entity.getUserId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL, DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        return bomUserMap;
    }

    @Override
    public Integer deleteBatchUser(List<BomUserEntity> bomUserEntityList, String corpid, Integer del) throws XbbException {
        if (CollectionsUtil.isEmpty(bomUserEntityList)) {
            return 0;
        }
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(StringConstant.DEL, del);
        for (BomUserEntity entity : bomUserEntityList){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        Integer success = bomUserDao.deleteBatch(idList, corpid, del);
        paasEsModel.updateBatch(insertDTOList);
        return success;
    }


    @Override
    public Integer updateBatch(List<BomUserEntity> list, String corpid) throws XbbException {
        Integer success = bomUserDao.updateBatch(list, corpid);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        long now = DateTimeUtil.getInt();
        for (BomUserEntity entity : list){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(StringConstant.UPDATE_TIME, now);
            if (Objects.nonNull(entity.getDel())) {
                map.put(StringConstant.DEL, entity.getDel());
            }
            JSONObject object = new JSONObject();
            if (Objects.nonNull(entity.getIsMain())) {
                object.put(BomTeamEnum.IS_MAIN.getDataAttr(), entity.getIsMain());
            }
            if (Objects.nonNull(entity.getDataId())) {
                object.put(BomTeamEnum.DATA_ID.getDataAttr(), entity.getDataId());
            }
            if (Objects.nonNull(entity.getUserId())) {
                object.put(BomTeamEnum.USER_ID.getDataAttr(), entity.getUserId());
            }
            if (Objects.nonNull(entity.getUserName())) {
                object.put(BomTeamEnum.USER_NAME.getDataAttr(), entity.getUserName());
            }
            if (Objects.nonNull(entity.getUserAvatar())) {
                object.put(BomTeamEnum.USER_AVATAR.getDataAttr(), entity.getUserAvatar());
            }
            if (!object.isEmpty()) {
                map.put(StringConstant.JSON_DATA, object);
            }
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        return success;
    }

    /**
     * 更新协同人可编辑权限
     *
     * @param bomUserEntity
     */
    @Override
    public void updateEditFormPer(BomUserEntity bomUserEntity) throws XbbException {
        updateFormTeam(bomUserEntity);
    }

    /**
     * 编辑团队成员标签
     *
     * @param bomUserEntity
     */
    @Override
    public void editLabel(BomUserEntity bomUserEntity) throws XbbException {
        updateFormTeam(bomUserEntity);
    }


    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        bomUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    private void updateFormTeam(BomUserEntity bomUserEntity) throws XbbException{
        Long updateTime = DateTimeUtil.getInt();
        bomUserEntity.setUpdateTime(updateTime);
        bomUserDao.update(bomUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = bomUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_BOM_TEAM.getType() + "_" + corpid + "_" + bomUserEntity.getId());
        insertDTO.setParent(corpid + "_" + bomUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_BOM_TEAM);
        paasEsModel.update(insertDTO);
    }


}
